import { setToken, removeToken } from '@utils/auth'
import router, { resetRouter } from '@/router'
import Api from '../api'
import jwt from 'jsonwebtoken'
const state = {
	token: '',
	nickname: '',
	avatar: '',
	deptId: '',
	userId: ''
}

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_INFO: (state, info) => {
		const { nickname, avatar, userId, deptId } = info
		state.nickname = nickname
		state.avatar = avatar
		state.userId = userId
		state.deptId = deptId
	},
	RESET_INFO: state => {
		state.token = ''
		state.nickname = ''
		state.avatar = ''
		state.userId = ''
		state.deptId = ''
	}
}

const actions = {
	// 设置token和userInfo
	setJwtTokenAndInfo({ dispatch, commit }, token) {
		try {
			const info = jwt.decode(token)
			$http.setToken(token)
			commit('SET_TOKEN', token)
			commit('SET_INFO', info)
			return true
		} catch (error) {
			return false
		}
	},
	// 登录
	login({ dispatch }, userInfo) {
		const { username, password, code, sign } = userInfo
		return new Promise((resolve, reject) => {
			Api.login({
				username: username,
				password: password,
				grant_type: 'password',
				code,
				sign
			})
				.then(response => {
					const token = response
					$http.setToken(token)
					dispatch('setJwtTokenAndInfo', token)
					setToken(token)
					resolve()
				})
				.catch(error => {
					reject(error)
				})
		})
	},
	// 登出
	loginOut({ commit }) {
		return new Promise((resolve, reject) => {
			commit('RESET_INFO')
			$http.clearToken()
			removeToken()
			resetRouter()
			if (router.currentRoute.path === '/') {
				router.push({ path: '/login' })
			} else {
				router.push({ path: `/login?redirect=${router.currentRoute.path}` })
			}
			resolve()
		})
	},
	// 移除token
	resetToken({ commit }) {
		return new Promise(resolve => {
			commit('RESET_INFO')
			removeToken()
			resolve()
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
